#include <types.h>
#include <system/libk.h>

void	bcopy(const void *src, void *dest, uint_t n)
{
    const char_t* s = (const char_t *)src;
    char_t *d = (char_t *)dest;
    if (s <= d)
        for (; n>0; --n)
            d[n-1] = s[n-1];
    else
        for (; n>0; --n)
            *d++ = *s++;
}

void	bzero(void *dest, uint_t n)
{
    memset(dest, 0, n);
}

void	*memcpy(void *dest, const void *src, uint_t n)
{
    bcopy(src, dest, n);
    return dest;
}

void	*memset(void *dest, int_t c, uint_t n)
{
    char_t *d = (char_t *)dest;
    for (; n>0; --n)
        *d++ = (char_t)c;
    return dest;
}

int_t	memcmp(const void *s1, const void *s2, uint_t n)
{
    const char_t *s3 = (const char_t *)s1;
    const char_t *s4 = (const char_t *)s2;
    for (; n>0; --n) {
        if (*s3 > *s4)
            return 1;
        else if (*s3 < *s4)
            return -1;
        ++s3;
        ++s4;
    }
    return 0;
}

int_t	strcmp(const char_t *s1, const char_t *s2)
{
    while (*s1 && *s2) {
        int_t r = *s1++ - *s2++;
        if (r)
            return r;
    }
    if (*s1 == *s2)
        return 0;
    else
        return (*s1)?1:-1;
}

char_t	*strcpy(char_t *dest, const char_t *src)
{
    char_t *p = dest;
    while ( (*dest++ = *src++))
        ;
    *dest = 0;
    return p;
}

uint_t	strlen(const char_t *s)
{
    uint_t n = 0;
    while (*s++)
        ++n;
    return n;
}

void out(ushort_t _port, uchar_t _data)
{
	asm volatile("outb %1, %0" : : "dN" (_port), "a" (_data));
}

uchar_t in(ushort_t _port)
{
	uchar_t rv;
	asm volatile("inb %1, %0" : "=a" (rv) : "dN" (_port));
	return rv;
}

